﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Core.Dtos;
using Core.Messages;
using Core.Queries;
using Core.IRepository;
using Core.Domain;
using Library.Helpers;
using Front.Controllers.Api;
using Core.IGateways;
using System.IO;
using System.Collections;
using Core.IServices;
using Library.Logging;
using Core.Factories;
using Core.Context;
using System.Web.Http.Cors;
using Share.Enterprise.Api;

namespace Front.Controllers.Api
{
    [RoutePrefix("api/policies")]
    [EnableCors(origins: "*", headers: "*", methods: "*")]
    //[Authorize]
    public class PolicyApiController : ApiController, ICrudApiController<int, PolicyDto, MotorPolicyDto, PolicyQuery>, IQueryApiController<int, PolicyDto, PolicyQuery>
    {
        private readonly IPolicyService service;
        private readonly IRequestFactory requestFactory;
        private readonly ICurrentContext currentContext;

        public PolicyApiController(IPolicyService policyService, ILogger Logger, ICurrentContext currentContext, IRequestFactory requestFactory)            
        {
            this.service = policyService;
            this.requestFactory = requestFactory;
            this.currentContext = currentContext;
        }
                       
        [HttpPost]
        [Route("searches")]
        public QueryResponse<PolicyDto> FindBy(PolicyQuery query)
        {
            Request<PolicyQuery> request = requestFactory.GetInstance<PolicyQuery>(query);
            return service.FindBy(request);
        }

        [Route("{id}")]
        public PolicyDto Get(int id)
        {
            return service.FindByID(id);
        }

        [HttpPost]
        [Route("")]
        public virtual Response<int> Post(MotorPolicyDto dto)
        {
            Request<PolicyDto> request = requestFactory.GetInstance<PolicyDto>(dto);
            return service.Add(request);
        }

        [HttpPut]
        [Route("{id}")]
        public virtual Response Put(int id, MotorPolicyDto dto)
        {
            Request<PolicyDto> request = requestFactory.GetInstance<PolicyDto>(dto);
            return service.Edit(id, request);
        }

        [HttpDelete]
        [Route("{id}")]
        public virtual Response Delete(int id)
        {
            return service.Delete(id);
        }

        [HttpGet]
        [Route("{id:int}/document")]
        public HttpResponseMessage Document(int id)
        {
            Stream fileStream = service.BuildReport(id);
            return HttpResponseMessageHelper.CreatePDFResponse(fileStream, "policy.pdf");
        }

        [HttpPut]
        [Route("{id:int}/state")]
        public Response<PolicyDto> Put(int id, DoActionRequest request)
        {
            request.UserId = currentContext.UserId;
            return service.DoAction(id, request);
        }
    }
}